import * as THREE from 'three';
import { geoMercator } from 'd3'

let mercatorConversion = null;
let properties = null
let mapMesh = new THREE.Group()
let lineMesh = new THREE.Group()
const useMap = (data, extrudeSettings = {
  steps: 1,
  depth: 0.18,
  bevelEnabled: false,
}) => {
  const features = data.features
  properties = features[0].properties
  mercatorConversion = geoMercator().center(properties.center).scale(200).translate([0, 0]); // 设置中心点并得到坐标转换函数
  // console.log(data, 'mapdata')
  features.forEach(ele => {
    const coordinates = ele.geometry.coordinates
    const properties = ele.properties
    coordinates.forEach(item => {
      item.forEach(it => {
        const shape = new THREE.Shape()
        let points = new Array()
        it.map((point, i) => {
          const [x, y] = mercatorConversion(point)
          i !== 0 ? shape.lineTo(x, -y) : shape.moveTo(x, -y)
          points.push(new THREE.Vector3(x, -y, extrudeSettings.depth + 0.008))
        })
        const lineGeo = new THREE.BufferGeometry()
        lineGeo.setFromPoints(points)
        const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff })
        let line = new THREE.Line(lineGeo, lineMaterial)
        line.name = properties.name
        lineMesh.add(line)
        // 对shape对象进行拉伸
        // const extrudeSettings = {
        //   steps: 1,
        //   depth: 0.18,
        //   bevelEnabled: false,
        //   bevelThickness: 0.001,
        //   bevelSize: 0.03,
        //   bevelOffset: 0,
        //   bevelSegments: 3
        // };
        const extrudeGeo = new THREE.ExtrudeGeometry(shape, extrudeSettings)
        const material = new THREE.MeshPhongMaterial({
          color: 0x888888,
          // emissive: 0xffffff,
          // emissiveIntensity: 0.2,
        })
        const materialSide = new THREE.MeshPhongMaterial({
          color: 0x07fbfb,
          wireframe: true
        })
        let mesh = new THREE.Mesh(extrudeGeo, [material, materialSide])
        const [c_x, c_y] = mercatorConversion(properties.center)
        mesh._center = [c_x, -c_y]
        // console.log(mesh._center, properties.name)
        mapMesh.add(mesh)
        mesh.name = properties.name
        // console.log(mesh.name, 'mapmeshname')
      })
    })
  });
  return { mapMesh, lineMesh, mercatorConversion }
}

export { useMap }